package com.xuan.collegeblog.spider.service.Impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.moxi.mogublog.xo.global.SysConf;
import com.moxi.mogublog.xo.service.xuan.CollegeService;
import com.moxi.mogublog.commons.vo.college.CollegeVo;
import com.xuan.collegeblog.spider.service.BaiduService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class BaiduServiceImpl implements BaiduService {


    private static final String TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token";
    private static final String CHAT_URL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-speed-128k?access_token=";
    private static final String CLIENT_ID = "YSP29lRMYxRlh4HdGNoHDnvx";
    private static final String CLIENT_SECRET = "miBUIywnAxcmeQatdx30T2rKmyyA1az2";


    @Autowired
    private CollegeService collegeService;

    /**
     * @param content
     * @return java.lang.String
     * @Description: 异步处理爬虫数据
     * @Author: huangzx
     * @Date: 2024/7/18 8:58
     */
    @Override
    @Async("asyncTaskExecutor")
    public String processContent(String content, Long collegeId) {
        // 假设这里是调用百度API的逻辑
        // 这里只是一个示例，具体实现需要根据你的业务需求来编写
        // System.out.println("Processing content with clientId: " + clientId + ", clientSecret: " + clientSecret + ", content: " + content);

        String accessToken = getAccessToken(CLIENT_ID, CLIENT_SECRET);
        if (accessToken == null) {
            return "Failed to get access token.";
        }
        // System.out.println(accessToken);
        // 创建params字典并添加到列表中

        Map<String, Object> params = new HashMap<>();
        params.put("role", "user");
        params.put("content", content);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("messages", Arrays.asList(params));
        // 发送请求
        RestTemplate restTemplate = new RestTemplate();
        String url = CHAT_URL + accessToken;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String requestBodyJson = objectMapper.writeValueAsString(requestBody);
            // 使用 requestBodyJson 替换原来的 requestBody
            HttpEntity<String> requestEntity = new HttpEntity<>(requestBodyJson, headers);
            ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
//            log.info("response: {}", response.getBody());
            try {
                JsonNode rootNode = objectMapper.readTree(response.getBody());
                String result = rootNode.path("result").asText();
                log.info("result: {}", result);
                Pattern pattern = Pattern.compile("标题：(.+?)简介：(.+?)内容：(.*)", Pattern.DOTALL);
                Matcher matcher = pattern.matcher(result);
                if (matcher.find()) {
                    log.info("Found match");
                    CollegeVo collegeVo = new CollegeVo();
                    String resTitle = matcher.group(1).trim();  // 标题
                    String resSummary = matcher.group(2).trim();  // 简介
                    String resContent = matcher.group(3).trim();  // 内容
                    // 清除无法编码的字符
                    resTitle = resTitle.replaceAll("[^\\p{L}\\p{M}\\p{Z}\\p{N}\\p{P}\\p{S}]", "");
                    resSummary = resSummary.replaceAll("[^\\p{L}\\p{M}\\p{Z}\\p{N}\\p{P}\\p{S}]", "");
                    resContent = resContent.replaceAll("[^\\p{L}\\p{M}\\p{Z}\\p{N}\\p{P}\\p{S}]", "");

                    log.info("Title: {}, Summary: {}, Content: {}", resTitle, resSummary, resContent);
                    collegeVo.setTitle(resTitle);
                    collegeVo.setSummary(resSummary);
                    collegeVo.setContent(resContent);
                    collegeVo.setCollegeSortUid(String.valueOf(collegeId));
                    collegeVo.setOpenComment(SysConf.CAN_COMMENT);
                    collegeVo.setArticlesPart("微博出品");
                    collegeVo.setIsPublish("1");
                    collegeVo.setAuthor("自动生成机器人");
                    boolean isSuccess = collegeService.addCollege(collegeVo);
                    if (isSuccess) {
                        log.info("College added successfully: {}", collegeVo);
                    } else {
                        log.error("Failed to add college: {}", collegeVo);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return response.toString();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return "Failed to serialize request body to JSON.";
        }
    }


    /**
     * @param clientId
     * @param clientSecret
     * @return java.lang.String
     * @Description: 配套使用方法
     * @Author: huangzx
     * @Date: 2024/7/18 8:57
     */
    private String getAccessToken(String clientId, String clientSecret) {
        // 这里应该替换为你的client_id和client_secret

        // 构建请求体
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("grant_type", "client_credentials");
        params.add("client_id", clientId);
        params.add("client_secret", clientSecret);

        // 发送请求
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
        ResponseEntity<Map> response = restTemplate.postForEntity(TOKEN_URL, requestEntity, Map.class);

        // 从响应中获取access_token
        if (response.getStatusCode().is2xxSuccessful()) {
            Map<String, Object> result = response.getBody();
            return (String) result.get("access_token");
        }
        return null;
    }
}
